package chalmers.game.subterranean.model;

import java.util.Timer;
import java.util.TimerTask;

import chalmers.game.subterranean.event.Bus;
import chalmers.game.subterranean.event.events.ClockTickEvent;

/**
 * Used to call the progressTime() method in ISubterranean at regular intervalls.
 * 
 * @author Alex Evert
 */
public class Clock {

  /**
   * Creates a timerTask for a given model and call progressTime() repeatedly at the given
   * intervall.
   * 
   * @param ms The interval of the clock ticks in milleseconds.
   * @param model The model in wich time should be progressed.
   */
  public static void start(long ms, ISubterranean model) {
    Timer timer = new Timer();
    // Progress time once every ms milliseconds, begin by waiting.
    timer.scheduleAtFixedRate(new TimeProgressor(model), ms, ms);
  }

  /**
   * The task that will be run as a background process.
   */
  private static class TimeProgressor extends TimerTask {

    ISubterranean model;

    public TimeProgressor(ISubterranean model) {
      this.model = model;
    }

    @Override
    public void run() {
      model.progressTime();
      Bus.INSTANCE.post(new ClockTickEvent());
    }
  }
}
